<script setup>
import "normalize.css";
import {
  ArrowDown,
  ArrowRight, CameraFilled, CollectionTag, Compass,
  Document, EditPen,
  Expand, Film,
  Fold, Fries, Guide, Location,
  OfficeBuilding, PictureFilled,
  Printer, Reading, Setting, Tickets,
  TurnOff,
  User, UserFilled
} from "@element-plus/icons-vue";
import {computed, onMounted, reactive, ref, watch} from "vue";
import {onBeforeRouteUpdate, useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";
import {ElMessage} from "element-plus";
import uu from "@/util/uu";
let data = reactive({
  user:{
    nickName:"匿名用户",
  },
  isCollapse:false,
  text:'农业互助保险',
  dynamicBreadcrumb:[] //动态面包屑
})
//动态面包屑
const router = useRouter();
onMounted(()=>{
  router.afterEach(route => {
    //与给定路由地址匹配的标准化的路由记录数组。
    const  matchedRoutes =  route.matched;
    const dynamicBreadcrumb = []
    for (const route of matchedRoutes){
      if(route.meta && route.meta.breadcrumb){
        dynamicBreadcrumb.push({
          name:route.meta.breadcrumb,
          path:route.path
        })
      }
    }
    //赋值
    data.dynamicBreadcrumb = dynamicBreadcrumb
  })
})

// ====================>>>> 动态标签开始 ======================
const route = useRoute();
const store = useStore();

// 获取vuex里面所有的tag
const tagsList = computed(() => store.state.tagsList)
// 关闭一个标签
const closeTags = index => {
  //获取删除的标签的信息
  const delItem = tagsList.value[index];
  //让vuex删除指定的标签
  store.commit('delTagsItem', { index });
  // 如果关闭的是当前标签且标签不止一个，则激活前一个标签，如果关闭的是不是当前标签且标签不止一个，则激活后一个标签
  const item = tagsList.value[index] ? tagsList.value[index] : tagsList.value[index - 1];
  if (item) {
    // 如果删除的是当前标签，则跳往上面item判断好的目标标签的地址
    if (isActive(delItem.path)) {
      router.push(item.path)
    }
  } else {
    // 如果tagsList只有一个标签，删除了标签就没有标签，则跳转到首页
    // router.push("/");
    router.push("/Welcome");
  }
}

// 设置标签
const setTags = (route) => {
  const isExist = tagsList.value.some(item => item.path === route.fullPath)
  if (!isExist) {
    // tag超过5个就删除第一个
    if (tagsList.value.length >= 10) {
      store.commit('delTagsItem', { index: 1 })
    }
    store.commit('setTagsItem', {
      name: route.name,
      path: route.fullPath,
      title: route.meta.title
    })
  }
}
//首次加载页面的时候便添加标签页
setTags(route);

// 监听路由变化，在当前页面即将要离开的时候触发
onBeforeRouteUpdate((to) => {
  setTags(to)
})

// 关全部标签
const closeAll = () => {
  store.commit('clearTags');
  router.push("/");
}

// 关闭其它标签
const closeOther = () => {
  const curItem = tagsList.value.filter(item => {
    return item.path === route.fullPath;
  })
  store.commit('clearTagsOther', curItem);
}
// 显示标签栏
const showTags = computed(() => tagsList.value.length > 0)

// 判断tag是否被激活,如果被激活就高亮当前标签
const isActive = path => path === route.fullPath
// ====================>>>> 动态标签结束 ======

// 验证token
let token = sessionStorage.getItem("token")
if (token == null || token == ''){
  ElMessage.error("登录已失效，请重新登录")
  router.push('/login')
  // return;
}else {
  // ElMessage.error("!!!!!!!!!!!")
}

/**
 * 获取用户信息
 */
const queryUser = () => {
  uu.get("/user/getUser").then((result) => {
    if (result.ok){
      data.user = result.data;
      console.log("获取到的单个记录信息为" + JSON.stringify(data.user));
    }else {
      ElMessage.error(res.message)
    }
  });
}
queryUser()
/**
 * 登出
 */
const loginOut = () => {
  sessionStorage.clear(); // 清除令牌
  ElMessage({
    message: "退出登录成功",
    type: "success",
  });
  router.push('/') // 做默认登录页
}

// 折叠开
const foldOpen = () => {
  // 折叠效果，开
  data.isCollapse = true;
  data.text='x'
}
// 折叠关
const foldClose = () => {
  // 折叠效果，开
  data.isCollapse = false;
  setTimeout(()=>{ // 超时
    data.text='农业互助保险'
  },500)
}

/*
解决这个问题
ERROR ResizeObserver loop completed with undelivered notifications.
handleError@webpack-internal:///./node_modules/webpack-dev-server/client/overlay.js:299:58 createOverlay/
<@webpack-internal:///./node_modules/webpack-dev-server/client/overlay.js:318:18
 */
const debounce = (fn, delay) => {
  let timer = null;
  return function () {
    let context = this;
    let args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  }
}

const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
  constructor(callback) {
    callback = debounce(callback, 16);
    super(callback);
  }
}


</script>

<template>
  <div >
    <!-- 这是一个布局组件 -->
    <div class="common-layout" style="border: 1px solid #cccccc">
      <el-container style="height: 100vh;" >
        <!--   左侧   -->
        <!--   style 该为事件后，就需要一些特殊的格式。如下所示。花括号、去驼峰、逗号做分隔   -->
        <el-aside  width="200" style="background-color: white ;  border-right: 1px solid #cccccc " >
          <div style=" height: 59px;color: pink;  border: 1px solid #cccccc; font-size: 25px;font-family: 楷体,serif;text-align: center;line-height: 60px">
            <!-- 管理系统 -->
            <template v-if="!data.isCollapse">
              {{data.text}}
            </template>
            <template v-else>
              <el-icon><Guide /></el-icon>
            </template>
          </div>
          <div>
            <el-menu
                :collapse-transition="true"
                default-active="2"
                class="el-menu-vertical-demo"
                :collapse="data.isCollapse"
                @open="handleOpen"
                @close="handleClose"
                ref="menu"
                router
            >
              <el-sub-menu index="1">
                <template #title>
                  <el-icon><location /></el-icon>
                  <span>保单管理&nbsp;&nbsp;&nbsp;&nbsp;</span>
                </template>
                <el-menu-item index="/insurancePolicy"><el-icon><Film /></el-icon>保单信息</el-menu-item>
              </el-sub-menu>
              <el-sub-menu index="2">
                <template #title>
                  <el-icon><Tickets /></el-icon>
                  <span>报案管理</span>
                </template>
                <el-menu-item  index="/claimReport"><el-icon><Fries /></el-icon>报案信息</el-menu-item>
              </el-sub-menu>
              <el-sub-menu index="3">
                <template #title>
                  <el-icon><CollectionTag /></el-icon>
                  <span>调度管理</span>
                </template>
                <el-menu-item  index="/assign"><el-icon><Reading /></el-icon>任务指派</el-menu-item>
                <el-menu-item  index="/dispatch"><el-icon><EditPen /></el-icon>调度信息</el-menu-item>
                <el-menu-item  index="/survey"><el-icon><Compass /></el-icon>查勘信息</el-menu-item>
              </el-sub-menu>
              <el-sub-menu index="4">
                <template #title>
                  <el-icon><CameraFilled /></el-icon>
                  <span>图片管理</span>
                </template>
                <el-menu-item  index="/BusImages"><el-icon><PictureFilled /></el-icon>信息采集</el-menu-item>
              </el-sub-menu>
              <el-sub-menu index="5">
                <template #title>
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>企业管理</span>
                </template>
                <el-menu-item  index="/BusinessMessage"><el-icon><Document /></el-icon>企业信息</el-menu-item>
                <el-menu-item  index="/WorkingPersonnel"><el-icon><UserFilled /></el-icon>员工信息</el-menu-item>
              </el-sub-menu>
              <el-sub-menu index="6">
                <template #title>
                  <el-icon><Setting /></el-icon>
                  <span>系统管理</span>
                </template>
                <el-menu-item  index="/AreaManagement"><el-icon><Fries /></el-icon>省市信息...</el-menu-item>
              </el-sub-menu>
            </el-menu>
          </div>
        </el-aside>
        <el-container>
          <!--   头部   文字默认居中显示   border: 1px solid #cccccc -->
          <el-header >
            <div style="display: flex;width: 100%;height: 100%">
              <div style="display: flex;flex: 1;align-items:center">

                <el-icon v-if="data.isCollapse === false" style="cursor: pointer" @click="foldOpen()"><Fold /></el-icon>
                <el-icon v-if="data.isCollapse === true" style="cursor: pointer" @click="foldClose()"><Expand /></el-icon>
                <!--面包屑-->
                <el-breadcrumb :separator-icon="ArrowRight" style="display: inline-block;margin-left: 10px">
                  <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
                  <!--动态面包屑-->
                  <el-breadcrumb-item v-for="(item,index) in data.dynamicBreadcrumb" :key="index">{{item.name}}</el-breadcrumb-item>
                </el-breadcrumb>
                <!--          <el-breadcrumb separator="/" style="margin-left: 10px">-->
                <!--            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>-->
                <!--            <el-breadcrumb-item >系统用户</el-breadcrumb-item>-->
                <!--            <el-breadcrumb-item>用户数据</el-breadcrumb-item>-->
                <!--          </el-breadcrumb>-->
              </div>
              <div style="width: 100px;display: flex;align-items:center">
                <el-dropdown>
<!--                <span class="el-dropdown-link">-->
<!--                   欢迎，{{data.user.nickName}}-->
<!--&lt;!&ndash;                  <el-avatar shape="square" />&ndash;&gt;-->
<!--&lt;!&ndash;                  <el-icon class="el-icon&#45;&#45;right" style="width: 100%;height: 100%">&ndash;&gt;-->
<!--&lt;!&ndash;                  &ndash;&gt;-->
<!--&lt;!&ndash;                  </el-icon>&ndash;&gt;-->
<!--&lt;!&ndash;                  <arrow-down />&ndash;&gt;-->

<!--                </span>-->
                  <span class="el-dropdown-link">
                  欢迎，{{ data.user.nickName }}
                  <arrow-down style="width: 20px;height: 10px"/> <!-- 这里是一个箭头图标示例，你可以使用任何你想要的图标 -->
                </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>修改密码</el-dropdown-item>
                      <el-dropdown-item>个人中心</el-dropdown-item>
                      <el-dropdown-item @click="loginOut()">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-header>
          <!-- 动态标签tags栏 -->
          <div class="tagList" v-if="showTags">
            <ul>
              <li v-for="(item, index) in tagsList" :class="{ 'active': isActive(item.path) }"
                  :key="index">
                <router-link :to="item.path" class="tag" >
                  {{ item.title }}
                </router-link>
                <el-icon v-if="item.title!='首页'" @click="closeTags(index)" class="close">
                  <Close style="font-size: 11px;"/>
                </el-icon>
              </li>
            </ul>
            <!--            <el-dropdown>
                          <el-button type="primary">
                            标签选项
                            <el-icon>
                              <ArrowDown />
                            </el-icon>
                          </el-button>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item @click.native="closeOther">关闭其它</el-dropdown-item>
                              <el-dropdown-item @click.native="closeAll">关闭所有</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>-->

          </div>

          <!--   主体    style=" height: 100vh ; display: flex; " -->
          <el-main style="border-top: 1px solid #cccccc">
            <!-- Main 这里放置右侧的内容  -->
            <router-view></router-view><!-- 子路由的组件将会显示在这里 -->
          </el-main>
        </el-container>
      </el-container>
    </div>
  </div>

</template>

<style scoped>


</style>